import http from '../utils/http';
import { ALL_QUESTIONS,ADD_QUESTION } from './types';

export function setQuestions(questions,count) {
  return {
    type: ALL_QUESTIONS,
    questions,
    count
  };
}

export function addQuestions(result) {
  return {
    type: ADD_QUESTION,
    result
  };
}
// {category:this.props.selectedCategory,page: pagination.current,results: pagination.pageSize}
export function loadQuestions(category,page,pageSize) {
    page = typeof page !== 'undefined' ? page : 1;
    pageSize = typeof pageSize !== 'undefined' ? pageSize : 10;
    let data = {
      category:category,
      page:page,
      pageSize:pageSize
    }
    return dispatch => {
      return http.get('/api/questions',{
              params: data }).then(res => {
            if (res.data.code !== 10200 ){
              dispatch(setQuestions({data:[],state:"failed", message:res.data.message}));
            }else {
              dispatch(setQuestions(res.data.body.questions, res.data.body.total));
            }
            return res ;
          });
    }
}

export function getQuestion(id) {
  return dispatch => {
    return http.get('/api/questions/'+id).then((res) => {
        return res ; 
    })
  }
}

export function updateQuestion(data){
  return dispatch => {
      return http.post('/api/questions/update',data).then(res => {
              return res ;
            });
      }
}

export function addQuestion(data) {
    return dispatch => {
      return http.post('/api/questions/add',data).then(res => {
              return res ;
            });
      }
}

export function deleteQuestions(questionIDs){
    return dispatch => {
      return http.post('/api/questions/delete', {ids:questionIDs}).then(res => {
            return res ; 
        });
    }
}